package main

import (
	"fmt"
	"github.com/nats-io/nats"
	"log"
	"net/http"
	"os"
)

func healthz(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "OK")
}

func main() {
	uri := os.Getenv("NATS_URI")
	if uri == "" {
		uri = "nats://localhost:4222"
	}
	var err error
	var nc *nats.Conn

	nc, err = nats.Connect(uri)
	if err != nil {
		log.Fatal("无法链接到NATS服务器:", err)
	}
	fmt.Println("已连接到NATS服务器:", nc.ConnectedUrl())

	// 订阅
	nc.Subscribe("task", func(m *nats.Msg) {
		fmt.Printf("获取到消息request的subject:%s, data:%s", m.Subject, m.Data)
		fmt.Printf("[test....]重新返回pub的subject为:%s", m.Reply)
		nc.Publish(m.Reply, []byte("Done!"))
	})

	fmt.Println("Worker subscribed to 'tasks' for processing requests...")
	fmt.Println("Server listening on port 8181...")

	http.HandleFunc("/healthz", healthz)
	if err := http.ListenAndServe(":8181", nil); err != nil {
		log.Fatal(err)
	}

}
